// 文件路径: src/components/TaggedSearchableDropdown.js
import React, { useState, useRef } from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Chip from '@mui/material/Chip';
import Button from '@mui/material/Button';

const TaggedSearchableDropdown = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);
  const [open, setOpen] = useState(false); // 新增：用于控制下拉列表的打开和关闭
  const autocompleteRef = useRef(null);
  const predefinedOptions = [
    { label: 'Option 1' },
    { label: 'Option 2' },
    { label: 'Option 3' }
    // ...其他选项
  ];

  const handleFocus = (event) => {
    console.log('--------------------------------------------------------------'); // 打印更多信息
    console.log('获得焦点', event); // 打印更多信息
    setOpen(true);
  };

  const handleBlur = (event) => {
    console.log('失去焦点', event); // 打印更多信息
    setOpen(false);
  };

  const handleChange = (event, newValue) => {
    console.log('下拉列表变化', event); // 打印更多信息
    setSelectedOptions(newValue);
    setOpen(true); // 保持下拉列表的开放状态
  };

  return (
    <div>
      <Autocomplete
        ref={autocompleteRef}
        multiple
        freeSolo
        options={predefinedOptions}
        getOptionLabel={(option) => option.label}
        value={selectedOptions}
        onChange={handleChange} // 修改这里，用于调试
        // onChange={(event, newValue) => {
        //   setSelectedOptions(newValue);
        // }}
        open={open} // 控制下拉列表的显示
        renderTags={(value, getTagProps) => value.map((option, index) => <Chip label={option.label} {...getTagProps({ index })} />)}
        filterOptions={(options, params) => options} // 关闭搜索功能，始终显示所有选项
        renderInput={(params) => {
          console.log('绘制参数renderInput params:', params); // 打印更多信息
          return <TextField {...params} label="Tagged Search" onFocus={handleFocus} onBlur={handleBlur} />;
        }}
      />
      <Button onClick={handleFocus}>添加更多</Button>
    </div>
  );
};

export default TaggedSearchableDropdown;
